package com.dblog.server.servlets;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dblog.server.Messages;
import com.dblog.server.core.PMF;
import com.dblog.server.model.tblog.Post;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.api.datastore.Text;

public class Blog extends Core {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5917314819729817416L;

	public Blog(HttpServletRequest req, HttpServletResponse rsp) {
		super(req, rsp);
	}

	public void indexAction() throws IOException {

		PersistenceManager pm = PMF.get().getPersistenceManager();
		String query = "select from " + Post.class.getName();
		@SuppressWarnings("unchecked")
		List<Post> posts = (List<Post>) pm.newQuery(query).execute();
		Request.setAttribute("posts", posts);

	}

	public void newAction() throws IOException {
		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        if (user == null) {
        	Response.sendRedirect(userService.createLoginURL(Request.getRequestURI()));
        }
		
		if (Request.getMethod().contentEquals("POST")) {
			(new Messages(Request)).addMessage("Post added");
			Post post = new Post();
			post.setAuthor(user);
			post.setContent(new Text(Request.getParameter("content")));
			post.setTags(Request.getParameter("tags"));
			post.setDate(new Date());
			post.setTitle(Request.getParameter("title"));

			PersistenceManager pm = PMF.get().getPersistenceManager();
			try {
				pm.makePersistent(post);
			} finally {
				pm.close();
			}
			//Response.sendRedirect("/blog");
			return;
		}
	}

}
